import React, { Component } from 'react';
import IceContainer from '@icedesign/container';
import {
  FormBinderWrapper as IceFormBinderWrapper,
  FormBinder as IceFormBinder,
  FormError as IceFormError,
} from '@icedesign/form-binder';
import { Table, Button, Input, Select, Grid, DatePicker, Dialog, Radio, CascaderSelect, Icon, Feedback, Tab } from '@icedesign/base';
import { FormBinderWrapper, FormBinder } from '@icedesign/form-binder';
import CellEditor from './CellEditor';
import './EditableTable.scss';
import { enquireScreen } from 'enquire-js';
import cookie from 'react-cookies';
import axios from 'axios';
import ComplexDialog from "../ComplexDialog/ComplexDialog";
const { RangePicker } = DatePicker;
import PropTypes from 'prop-types';

const { Row, Col } = Grid;
const { Group: RadioGroup } = Radio;
const Toast = Feedback.toast;
const generatorData = () => {
  return Array.from({ length: 0 }).map((item, index) => {
    return {
      // todo: `待办事项 ${index}`,
      // memo: `备注说明文案 ${index}`,
      // validity: '2017-12-12',
    };
  });
};
const displayRender = labels => {
  return labels.reduce((ret, label, index) => {
    ret.push(
      <span className="label-ellipsis" title={label}>
        {label}
      </span>
    );
    if (index < labels.length - 1) {
      ret.push(<span className="label-separator"> / </span>);
    }
    return ret;
  }, []);
};

export default class EditableTable extends Component {
  static displayName = 'EditableTable';

  static propTypes = {};

  static defaultProps = {};

  constructor(props) {
    super(props);
    EditableTable.contextTypes = {
      router: PropTypes.object.isRequired
    }
    this.state = {
      formValue: {},
      isMobile: false,
      visible: false,
      _id: 1,
      changeOnSelect: false,
      data: {},
      value: {
        eDepAndeType: '',
        startDate: '',
        endDate: '',
        indexsInfo: [],
      },
      dataSource: [],
      data: []
    };

  }
  getDepart = () => {
    let value = this.props.value
    value = value === '高校单位指标' ? '事业(高校)管理员' : value
    value = value === '企业单位指标' ? '企业管理员' : value
    console.log("vvvvv", value)
    const baseurl = 'http://39.105.21.199:8989/IPEvaluation';
    const iwParentSeq = 0;
    const weighturl = `${baseurl}/userMamage/userDepartmentList.do?rName=${value}&sessionId=`
    const sessionid = cookie.load('sessionId');
    axios.get(weighturl + sessionid).then((res) => {
      const data = res.data.data;
      console.log("data---<", res)
      const selects = [];
      for (let _item in data) {
        selects.push(
          {
            label: data[_item],
            value: data[_item]
          }
        );
      }
      // data.map((item) => {
      //   select.label = item
      //   select.value = item
      //   console.log('seee', select)
      //   selects.push(select)
      // })
      this.setState({
        selects
      })

    })
  }

  tade = (e) => {

    console.log("eee", e)
    this.setState({
      w1: e
    })
  };
  componentWillMount() {
    this.getData(this.props.value)
    this.enquireScreenRegister();
    this.getDepart()
  }
  getData = (key) => {
    console.log('key,', key)
    key = key === '企业管理员' ? '企业单位指标' : key
    key = key === '高校管理员' ? '高校单位指标' : key
    if (cookie.load('user') !== '超级管理员') {
      const _value = this.state.value
      delete _value.eDepAndeType
      this.setState({
        value: _value
      })
    }


    const baseurl = 'http://39.105.21.199:8989/IPEvaluation';
    const iwParentSeq = 0;
    const weighturl = `${baseurl}/indexweightManage/showIndexweightList.do?iwType=${key}&sessionId=`
    const sessionid = cookie.load('sessionId');
    axios.post(weighturl + sessionid).then((response) => {
      console.log(" -->data", response);
      console.log("onload -->data", response.data.data);
      const tbdata = response.data.data;
      if (response.data.msg === 'LoginInvalidate') {
        Feedback.toast.error('您未登录或登录失效，请重新登录!')
        this.context.router.history.push('/pagelogin');
        return
      }

      console.log("children", tbdata[0]["children"])

      for (let i = 0; i < tbdata.length; i++) {
        if (tbdata[i]["children"] != null) {
          let tdata = tbdata[i]["children"]
          for (let j = 0; j < tdata.length; j++) {
            if (tdata[j]["children"] != null) {
              let data = tdata[j]["children"]
              for (let k = 0; k < data.length; k++) {
                data[k]["label"] = data[k]["iwName"];
                data[k]["value"] = data[k]["iwId"];
              }
            }
            tdata[j]["label"] = tdata[j]["iwName"];
            tdata[j]["value"] = tdata[j]["iwId"];
          }
        }
        tbdata[i]["label"] = tbdata[i]["iwName"];
        tbdata[i]["value"] = tbdata[i]["iwId"];
      }
      this.setState({ datass: tbdata });
    });
  }




  enquireScreenRegister = () => {
    const mediaCondition = 'only screen and (max-width: 720px)';

    enquireScreen((mobile) => {
      this.setState({
        isMobile: mobile,
      });
    }, mediaCondition);
  };

  showDialog = () => {
    const role = cookie.load('user');
    if (role === '普通用户') {
      Feedback.toast.error('您为普通用户不能执行此操作');
    } else {
      this.setState({
        visible: true,
      });
    }
  };
  hideDialog = () => {
    this.setState({
      visible: false,
    });
  };

  renderFooter = () => {
    return (
      <div style={styles.footer}>
        <Button onClick={this.hideDialog}>返回修改</Button>
        {/*<Button onClick={this.send()} type="primary">*/}
        {/*确认提交*/}
        {/*</Button>*/}
      </div>
    );
  };

  handleCheck = () => {
    this.setState({
      changeOnSelect: !this.state.changeOnSelect,
      value: null
    });
  }
  onInputChange = (e) => {
    try {
      const { _data } = this.state
      _data.number = parseInt(e);
      this.setState({
        _data
      })
    } catch (error) {
      //TODO
      console.log("sss")
    }

  }
  handleChange = (value, data, extra) => {
    console.log(value, data, extra);
    this.setState({
      data
    })
    const _data = {}
    _data.iwId = data.value
    _data.iwName = data.label
    delete data.value
    delete data.label
    delete data.pos
    Object.assign(_data, data);
    this.setState({
      _data
    })
    this.state.value.indexsInfo.push(_data);
  };
  renderOrder = (value, index) => {
    return <span>{index + 1}</span>;
  };
  deleteItem = (index) => {
    this.state.dataSource.splice(index, 1);
    delete this.state.value[index]
    this.state.value.indexsInfo.splice(index, 1)
    this.setState({
      dataSource: this.state.dataSource,
    });
  };
  renderInput = (value, index) => {
    return (
      <Input name="number" onChange={this.onInputChange} />
    );
  };
  renderOperation = (value, index) => {
    return (
      <Button onClick={this.deleteItem.bind(this, index)} shape="text">
        删除
      </Button>
    );
  };
  addItem = () => {
    const datass = this.state.datass
    const role = cookie.load('user');
    if (role === '普通用户') {
      Feedback.toast.error('您为普通用户不能执行此操作');
    } else {
      this.state.dataSource.push({
        todo: <CascaderSelect
          style={{ width: "480px" }}
          displayRender={displayRender}
          showItemCount="5"
          labelWidth="80"
          defaultValue="3431"
          dataSource={datass}
          onChange={this.handleChange}
        />
      });
      this.setState({
        dataSource: this.state.dataSource,
      });
      this.setState({
        value: this.state.value
      });
    }
  };

  formChange = values => {
    console.log('values', values);
    this.setState({
      values
    });
  };

  changeItem = () => {
    let items = this.state.value.items;
    items[0].aaa = '有趣';
    this.setState({
      value: {
        ...this.state.value,
        items: items
      }
    })
  };
  send = () => {
    const indexsInfo = "sss"
    // const indexsInfo = this.state.value
    console.log("value", this.state.value)
    const baseurl = 'http://39.105.21.199:8989/IPEvaluation';
    const sessionid = cookie.load('sessionId');
    const weighturl = `${baseurl}/evaluateManage/adminAddEvaluate.do?sessionId=${sessionid}`

    const param = new URLSearchParams();
    param.append('eDepAndeType', this.state.value.eDepAndeType);
    param.append('startDate', this.state.value.startDate);
    param.append('endDate', this.state.value.endDate);
    param.append('indexsInfo', JSON.stringify(this.state.value.indexsInfo, null, 2));
    axios.post(weighturl, param)
      .then((response) => {
        console.log("send-->response", response)
        this.setState({
          iw2: response.data.data
        })
        if (response.data.code === 0)
          Feedback.toast.success(response.data.msg);
        else
          if (response.data.code === 2)
            Feedback.toast.error(response.data.msg);

      }).catch((error) => {
        console.log(param)
      });
  }
  removeItem = (index) => {
    this.state.value.items.splice(index, 1);
    this.setState({
      value: this.state.value
    });
  }

  changeDataSource = (index, valueKey, value) => {
    this.state.dataSource[index][valueKey] = value;
    this.setState({
      dataSource: this.state.dataSource,
    });
  };

  renderEditor = (valueKey, value, index, record) => {
    return (
      <CellEditor
        valueKey={valueKey}
        index={index}
        value={record[valueKey]}
        onChange={this.changeDataSource}
      />
    );
  };


  // add = (e, name) => {
  //   console.log("eee", e);
  //   let _temp = ''
  //   for (let i = 0; i < this.state.iwName.length; i++) {
  //     if (e === this.state.iwName[i])
  //       _temp = this.state.iwSequence[i];
  //   }
  //   const baseurl = 'http://39.105.21.199:8989/IPEvaluation';
  //   const weighturl = baseurl + `/indexweightManage/showIndexweightList.do?iwParentSeq=${_temp}&sessionId=`
  //   const sessionid = cookie.load('sessionId');
  //   axios.post('./test.json').then((response) => {
  //     console.log("ssss123", response)
  //     this.setState({
  //       iw2: response.data.data
  //     })

  //     console.log(response.data.data)
  //     for (let i = 0; i < entitylist.length; i++) {
  //       this.state.weight2.push(entitylist[i]);
  //       this.state.iwId2.push(entitylist[i].iwId);
  //       this.state.iwName2.push(entitylist[i].iwName);
  //       this.state.iwParentseq2.push(entitylist[i].iwParentSeq);
  //       this.state.weight1_seq2.push(entitylist[i].weight1_Seq);
  //       this.state.iwSequence2.push(entitylist[i].iwSequence);
  //     }
  //   })
  // }

  submit = () => {
    this.setState({
      visible: false,
    });
  }
  onChanger = (sel) => {
    const { value } = this.props

    const _eDepAndeType = value === '高校单位指标' ? `${sel}_高校单位评价` : `${sel}_企业单位评价`  //这里处理的有点问题，如果出现 服务器异常，则可能出现 this.props.value  里没有值的情况，这时候只会显示 企业单位评价的查询结果
    const data = this.state.value
    data.eDepAndeType = _eDepAndeType
    this.setState({
      sel,
    })
  }
  render() {
    const { formValue } = this.state;
    const { isMobile } = this.state;
    const value = this.props.value
    const dialogStyle = {
      width: isMobile ? 'auto' : '640px',
      height: isMobile ? 'auto' : '340px',
    };
    const dataSource = this.state.selects
    console.log("this.state.dataSource", this.state.dataSource)
    console.log("this", this)
    return (
      <div className="editable-table" >
        {
          cookie.load('user') != '超级管理员' ? '' :
            <IceContainer title={`知识产权信息录入-${value}`}>
              <FormBinderWrapper values={this.state.formValue} onChange={this.formChange}>
                <Row wrap>
                  <Col xxs="24" l="8" style={styles.formCol}>
                    <FormBinder name="department">
                      <Select
                        size="large"
                        placeholder="所属单位"
                        onChange={this.onChanger}
                        value={this.state.sel}
                        dataSource={dataSource}
                      />
                    </FormBinder>
                  </Col>
                </Row>
              </FormBinderWrapper>
            </IceContainer>
        }
        <IceContainer>
          <div>
            选择时间区间：
            <RangePicker
              onChange={(val, str) => {
                const _value = this.state.value
                _value.startDate = str[0]
                _value.endDate = str[1]
                this.setState({
                  value: _value
                })

              }
              }
              onStartChange={(val, str) => console.log(val, str)}
            /><br />
            <div>
              <Table dataSource={this.state.dataSource} hasBorder={false}>
                <Table.Column width={80} title="顺序" cell={this.renderOrder} />
                <Table.Column
                  width={240}
                  title="一级指标/二级指标/三级指标"
                  cell={this.renderEditor.bind(this, 'todo')}
                />
                <Table.Column title="数据" width={80} cell={this.renderInput} />
                <Table.Column title="操作" width={80} cell={this.renderOperation} />
              </Table>
            </div>
            <IceFormBinderWrapper
              value={this.state.value}
              onChange={this.formChange}
              ref="form"
            >
              <div>
                <div style={{ marginTop: 20 }}>
                  <Button style={{ marginTop: 10 }} onClick={this.addItem}>新增一行 +</Button>
                  {/*<Button style={{ marginLeft: 10 }} onClick={this.validateAllFormField}>*/}
                  {/*校验整个表单*/}
                  {/*</Button>*/}
                  {/*<Button type="primary" onClick={this.send}>提交评价</Button>*/}

                  <Button type="primary" onClick={this.send} style={styles.submit}>
                    点击提交评价
              </Button>
                </div>
              </div>
            </IceFormBinderWrapper>
            {/*<div style={{ border: '1px solid #ccc', background: '#cacaca', marginTop: 20, padding: 10 }}>*/}
              {/*<strong>当前表单数据：</strong>*/}
              {/*<pre>{JSON.stringify(this.state.value, null, 2)}</pre>*/}
            {/*</div>*/}
          </div>
          <Dialog
            className="complex-dialog"
            style={{ ...dialogStyle }}
            autoFocus={false}
            footer={this.renderFooter()}
            title="确认添加"
            isFullScreen
            onClose={this.hideDialog}
            {...this.props}
            visible={this.state.visible}
          >
            <div style={styles.dialogContent}>
              <img
                style={styles.icon}
                src="//img.alicdn.com/tfs/TB1GOHLXyqAXuNjy1XdXXaYcVXa-52-52.png"
                srcSet="//img.alicdn.com/tfs/TB1h_K_b4rI8KJjy0FpXXb5hVXa-104-104.png"
                alt=""
              />
              <div style={styles.info}>
                您确定要提交评价信息么？
          </div>
              {/*<div style={styles.extraInfo}>*/}
              {/*角色是淘宝中对达人的XXX，通过角色您将获得特权*/}
              {/*</div>*/}
            </div>
          </Dialog>
        </IceContainer>
      </div>
    );
  }
}

const styles = {
  addNewItem: {
    background: '#F5F5F5',
    height: 32,
    lineHeight: '32px',
    marginTop: 20,
    cursor: 'pointer',
    textAlign: 'center',
  },
  submit: {
    background: '#3080fe',
    height: 32,
    lineHeight: '32px',
    marginTop: 50,
    cursor: 'pointer',
    textAlign: 'center',
    borderRadius: '6px',
    color: 'white',
    float: 'right',
  },
  formRow: {
    marginBottom: '18px',
  },
  formCol: {
    display: 'flex',
    alignItems: 'center',
    marginBottom: '20px',
  },
  label: {
    lineHeight: '28px',
    paddingRight: '10px',
  },
  icon: {
    width: '52px',
    height: '52px',
  },
  dialogContent: {
    // width: '640px',
    // height: '200px',
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
  },
  info: {
    marginTop: '10px',
    fontSize: '16px',
    textAlign: 'center',
  },
  extraInfo: {
    marginTop: '12px',
    fontSize: '12px',
    color: '#999999',
  },
  authList: {
    marginTop: '10px',
    fontSize: '12px',
    color: '#999999',
  },
  authItem: {
    marginTop: '5px',
  },
  authItemIcon: {
    color: '#2ECA9C',
    marginRight: '5px',
  },
  footer: {
    marginTop: '10px',
    marginBottom: '10px',
    textAlign: 'center',
  },
};
